<script setup>
import ShortCut from "@/components/ShortCut.vue";
import { useOrderStore } from "@/stores/order";
import { onMounted, ref, computed } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

// 使用订单 store
const orderStore = useOrderStore();
const loading = computed(() => orderStore.loading);
const activeTab = ref('all'); // 激活的标签: all, pending, completed
const searchQuery = ref(''); // 搜索关键词
const router = useRouter();

// 过滤和排序后的订单列表
const filteredOrders = computed(() => {
  let filtered = [...orderStore.orderList];
  
  // 根据标签过滤
  if (activeTab.value === 'pending') {
    filtered = filtered.filter(order => order.status === '0');
  } else if (activeTab.value === 'completed') {
    filtered = filtered.filter(order => order.status === '1');
  }
  
  // 根据搜索关键词过滤
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase().trim();
    filtered = filtered.filter(order => 
      order.recipient?.toLowerCase().includes(query) || 
      order.address?.toLowerCase().includes(query) ||
      order.books?.some(book => book.booksname?.toLowerCase().includes(query))
    );
  }
  
  // 按订单日期倒序排序
  return filtered.sort((a, b) => {
    return new Date(b.orderDate) - new Date(a.orderDate);
  });
});

// 处理删除订单
const handleDeleteOrder = async (orderId) => {
  await orderStore.deleteOrder(orderId);
};

// 刷新订单列表
const refreshOrders = () => {
  orderStore.getOrderList();
  ElMessage.success('订单列表已刷新');
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知日期';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 状态转换
const orderStatus = (status) => {
  switch(status) {
    case '0': return '待发货';
    case '1': return '已完成';
    default: return '未知状态';
  }
};

// 立即加载订单数据
onMounted(() => {
  orderStore.getOrderList();
});
</script>

<template>
  <div class="order-page">
    <ShortCut></ShortCut>
    
    <div class="order-container">
      <div class="order-header">
        <h1>我的订单</h1>
        <div class="order-actions">
          <el-input
            v-model="searchQuery"
            placeholder="搜索订单..."
            prefix-icon="el-icon-search"
            clearable
            class="search-input"
          />
          <el-button type="primary" @click="refreshOrders" :loading="loading">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </div>
      </div>
      
      <div class="order-stats">
        <div class="stat-card">
          <div class="stat-value">{{ orderStore.orderCount }}</div>
          <div class="stat-label">总订单数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ orderStore.pendingOrders.length }}</div>
          <div class="stat-label">待发货</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ orderStore.completedOrders.length }}</div>
          <div class="stat-label">已完成</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">¥{{ orderStore.totalOrderValue }}</div>
          <div class="stat-label">总消费</div>
        </div>
      </div>
      
      <el-tabs v-model="activeTab" class="order-tabs">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <el-tab-pane label="待发货" name="pending"></el-tab-pane>
        <el-tab-pane label="已完成" name="completed"></el-tab-pane>
      </el-tabs>
      
      <el-empty v-if="filteredOrders.length === 0" description="暂无订单"></el-empty>
      
      <div v-else class="order-list">
        <el-card v-for="order in filteredOrders" :key="order.order_id" class="order-card">
          <div class="order-card-header">
            <div class="order-info">
              <div class="order-number">订单号: {{ order.order_id }}</div>
              <div class="order-date">下单时间: {{ formatDate(order.orderDate) }}</div>
            </div>
            <div class="order-status" :class="{ 'status-pending': order.status === '0', 'status-completed': order.status === '1' }">
              {{ orderStatus(order.status) }}
            </div>
          </div>
          
          <div class="order-details">
            <div class="shipping-info">
              <h3>收货信息</h3>
              <p><strong>收货人:</strong> {{ order.recipient }}</p>
              <p><strong>联系电话:</strong> {{ order.phone }}</p>
              <p><strong>收货地址:</strong> {{ order.address }}</p>
            </div>
            
            <el-divider></el-divider>
            
            <div class="product-list">
              <h3>订单商品</h3>
              <el-table :data="order.books" stripe style="width: 100%">
                <el-table-column label="图片" width="100">
                  <template #default="scope">
                    <img :src="scope.row.img" :alt="scope.row.booksname" class="product-image">
                  </template>
                </el-table-column>
                <el-table-column prop="booksname" label="商品名称"></el-table-column>
                <el-table-column prop="price" label="单价" width="100">
                  <template #default="scope">
                    ¥{{ scope.row.price }}
                  </template>
                </el-table-column>
                <el-table-column prop="num" label="数量" width="70"></el-table-column>
                <el-table-column label="小计" width="120">
                  <template #default="scope">
                    ¥{{ (scope.row.price * scope.row.num).toFixed(2) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <div class="order-summary">
              <div class="order-total">订单总价: <span class="price">¥{{ order.totalprice }}</span></div>
              <div class="order-actions">
                <el-button type="primary" @click="router.push(`/order/${order.order_id}`)">
                  查看详情
                </el-button>
                <el-button type="danger" @click="handleDeleteOrder(order.order_id)" :disabled="loading">
                  删除订单
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<style scoped>
.order-page {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.order-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.order-header h1 {
  font-size: 24px;
  margin: 0;
  color: #333;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.order-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.stat-card {
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  margin-top: 5px;
  color: #606266;
}

.order-tabs {
  margin-bottom: 20px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  border-radius: 8px;
  overflow: hidden;
}

.order-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.order-number {
  font-weight: bold;
  margin-bottom: 5px;
}

.order-date {
  color: #909399;
  font-size: 14px;
}

.order-status {
  font-weight: bold;
  padding: 6px 12px;
  border-radius: 4px;
}

.status-pending {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status-completed {
  background-color: #f0f9eb;
  color: #67c23a;
}

.shipping-info {
  margin-bottom: 20px;
}

.shipping-info h3, .product-list h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #303133;
}

.shipping-info p {
  margin: 5px 0;
  color: #606266;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.order-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.order-total {
  font-size: 16px;
}

.price {
  font-weight: bold;
  color: #f56c6c;
  font-size: 18px;
}

@media (max-width: 768px) {
  .order-stats {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .order-card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .order-status {
    margin-top: 10px;
  }
  
  .order-summary {
    flex-direction: column;
    gap: 15px;
  }
}
</style>
